const fs = require('fs')
const { promisify } = require('util')

const { User } = require('../model')
const { createToken } = require('../utils/jwt')

const rename = promisify(fs.rename)

const list = async (req, res) => {
	const result = await User.find()
	res.status(200).json({ msg: result })
}

// 用户注册
const register = async (req, res) => {
	const userModel = new User(req.body)
	const dbBack = await userModel.save()
	const user = dbBack.toJSON()
	delete user.password
	res.status(201).json({ user })
}

// 用户登录
const login = async (req, res) => {
	// 客户端数据验证
	// 链接数据库查询
	let dbBack = await User.findOne(req.body)
	if (!dbBack) {
		res.status(402).json({ error: '邮箱或者密码不正确' })
	}

	dbBack = dbBack.toJSON()
	dbBack.token = await createToken(dbBack)
	res.status(200).json(dbBack)
}

const update = async (req, res) => {
	const updateData = await User.findByIdAndUpdate(
		req.user.userInfo._id,
		req.body,
		{
			new: true
		}
	)
	res.status(202).json({ user: updateData })
}

const headImage = async (req, res) => {
	/* {
		fieldname: 'headimage',
		originalname: 'b7372a75aacf183f8cabb8f2536fa4.jpg',
		encoding: '7bit',
		mimetype: 'image/jpeg',
		destination: 'public/',
		filename: '1b1b83834a682466dc7c8d1891d5de9f',
		path: 'public/1b1b83834a682466dc7c8d1891d5de9f',
		size: 252261
	} */
	const fileArr = req.file.originalname.split('.')
	const fileType = fileArr[fileArr.length - 1]
	try {
		await rename(
			`./public/${req.file.filename}`,
			`./public/${req.file.filename}.${fileType}`
		)
		res.status(201).json({ filepath: `${req.file.filename}.${fileType}` })
	} catch (error) {
		res.status(500).json({ error })
	}
}

module.exports = {
	register,
	login,
	list,
	update,
	headImage
}
